package com.wmx.thymeleafapp.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.wmx.thymeleafapp.pojo.User;
import com.wmx.thymeleafapp.utils.FileWmxUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.MapUtils;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.io.File;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangmaoxiong
 * @version 1.0
 * @date 2020/5/7 9:12
 */
@Controller
@ApiIgnore
public class ExampleController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RestTemplate restTemplate;

    /**
     * 跳转到修改页面，get 请求： http://localhost:8080/example/httpPut
     *
     * @return
     */
    @GetMapping("example/httpPut")
    public String toPutPage(Model model) {
        //待修改人员数据
        User user = new User(9527, "华安", 18990.98F, "本科", new Date());

        //学历下拉框数据
        String[] educationArr = {"研究生及以上", "本科", "大专", "高中", "初中及以下"};

        //往前端传递数据.
        model.addAttribute("user", user);
        model.addAttribute("educationArr", educationArr);
        return "examples/httpPut";
    }

    /**
     * 修改提交时调用此接口, put 请求:  http://localhost:8080/example/httpPut
     *
     * @param user
     * @return
     */
    @PutMapping("example/httpPut")
    @ResponseBody
    public String httpPut(User user) {
        //将数据返回给页面，不操作数据.
        String valueAsString = "{}";
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            valueAsString = objectMapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return valueAsString;
    }


    /**
     * http://localhost:8080/example/zTree
     * 跳转到 zTree.html 页面
     *
     * @return
     */
    @GetMapping("example/zTree")
    public String toZTree() {
        return "examples/zTree";
    }

    /**
     * http://localhost:8080/example/standardData
     * 跳转到 standardData.html zTree 标准数据展示页面
     *
     * @return
     */
    @GetMapping("example/standardData")
    public String toStandardData() {
        return "examples/standardData";
    }

    /**
     * http://localhost:8080/example/getStandardData
     * 用于 standardData.html zTree 标准数据展示页面获取 json 数据.
     *
     * @return
     */
    @GetMapping("example/getStandardData")
    @ResponseBody
    public String getStandardData() {
        File rootFile = new File("C:\\wmx\\document\\验收文档 20200429");
        JsonArray jsonArray = FileWmxUtils.fileTreeByDirPath(rootFile, 3);
        return jsonArray.toString();
    }

    /**
     * 1、@EnableRetry + @Retryable 注解优雅的实现循环重试功能
     * http://localhost:8080/fun/retryable
     *
     * @return
     */
    @GetMapping("fun/retryable")
    @ResponseBody
    @Retryable(value = {Exception.class}, maxAttempts = 5, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Map<String, Object> retryable() {
        System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "：开始请求天气信息...");
        Map<String, Object> forObject = restTemplate.getForObject("http://t.weather.sojson.com/api/weather/city/101030100", Map.class);
        System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss") + "：请求天气信息成功。");
        System.out.println(forObject);
        return forObject;

        // 当网络不通发生异常时，日志如下，直到重试到最后一次仍然未能成功，则抛出异常
        // 2022-05-21 12:55:45：开始请求天气信息...
        // 2022-05-21 12:55:47：开始请求天气信息...
        // 2022-05-21 12:55:50：开始请求天气信息...
        // 2022-05-21 12:55:50.945 ERROR 11480 java.net.UnknownHostException: t.weather.sojson.com
    }

    /**
     * redis 将信息发送到指定的频道
     * http://localhost:8080/redis/pub?topic=memoryCache&context=flushAll
     * http://localhost:8080/redis/pub?topic=basic-service&context=flushDb
     *
     * @param topic   ：消息所属的主题/频道
     * @param context ：消息内容
     * @return
     */
    @GetMapping("redis/pub")
    @ResponseBody
    public Map<String, Object> retryable(@RequestParam String topic, @RequestParam Object context) {
        /**
         * void convertAndSend(String destination, Object message): 将给定消息发布到给定通道
         * 1、 destination：要发布到的通道不能为 null
         */
        redisTemplate.convertAndSend(topic, context);
        Map<String, Object> dataMap = new HashMap<>(4);
        dataMap.put(topic, context);
        return dataMap;
    }


}
